﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.Utility;

namespace FileManager_Client.PresentationLayer
{
    public partial class FileLogs : Form
    {
        private List<string> _fileSidCollection;
        private WaitDialogForm _waitBeforeLogin;
        private FileService fileService;
        private static object _lockObj = new object();
        private static int PageNumber = 20;
        public FileLogs(List<string> fileSidCollection)
        {
            InitializeComponent();
            _fileSidCollection = fileSidCollection;
            fileService = new FileService();
            dgvLogList.AutoGenerateColumns = false;
        }

        private void btn_FirstPage_Click(object sender, EventArgs e)
        {
            CurrentPage = 1;
            SetControlEnable();
            GetFileLog();
        }

        private void SetControlEnable()
        {
            btn_FirstPage.Enabled = true;
            btn_PerviewPage.Enabled = true;
            btn_NextPage.Enabled = true;
            btn_LastPage.Enabled = true;
            if(CurrentPage == 1)
            {
                btn_FirstPage.Enabled = false;
                btn_PerviewPage.Enabled = false;
            }
            if(CurrentPage == PageCount)
            {
                btn_NextPage.Enabled = false;
                btn_LastPage.Enabled = false;
            }
        }

        private void btn_PerviewPage_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            SetControlEnable();
            GetFileLog();
        }

        private void btn_NextPage_Click(object sender, EventArgs e)
        {
            CurrentPage += 1;
            SetControlEnable();
            GetFileLog();
        }

        private void btn_LastPage_Click(object sender, EventArgs e)
        {
            CurrentPage = PageCount;
            SetControlEnable();
            GetFileLog();
        }

        private void btn_SkipTo_Click(object sender, EventArgs e)
        {
            var skipToNumber = int.Parse(tb_PageNumber.Text);
            if(skipToNumber == 0 || skipToNumber > PageCount) return;
            CurrentPage = skipToNumber;
            SetControlEnable();
            GetFileLog();
        }

        private void tb_PageNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar == 48)
            {
                if (tb_PageNumber.Text.Length <= 0)
                    e.Handled = true;
            }
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
                e.Handled = true;
        }

        private void FileLogs_Shown(object sender, EventArgs e)
        {
            try
            {
                lock (_lockObj)
                {
                    _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.GetFileLogStr,
                                                          GlobalString.System_Config_String.MbxInfoStr)
                    {
                        BackColor = BackColor
                    };
                    _waitBeforeLogin.Hide();
                }
                var backgroundWorkerGetCompanyInfo = new BackgroundWorker();
                backgroundWorkerGetCompanyInfo.DoWork += backgroundWorkerGetCompanyInfo_DoWork;
                var fileLogQueryArgs = new FileLogQueryArgs
                                           {
                                               FileSidCollectionk__BackingField = _fileSidCollection.ToArray()
                                           };
                backgroundWorkerGetCompanyInfo.RunWorkerAsync(fileLogQueryArgs);
                _waitBeforeLogin.ShowDialog();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("FileLogs_Shown has problem", ex);
                XtraMessageBox.Show("获取文件日志失败，请联系管理员!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
            }
        }

        void backgroundWorkerGetCompanyInfo_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var args = e.Argument as FileLogQueryArgs;
                var result = fileService.GetFileLogCount(args);
                 if (!IsHandleCreated)
                CreateHandle();
                 if (result.ResultExceptionk__BackingField == BaseExceptionEnum.GetFileLogCountException)
                 {
                     XtraMessageBox.Show("远程服务器异常，请联系管理员!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                         MessageBoxIcon.Error);
                     Invoke((EventHandler)delegate
                     {
                         Close();
                     });
                 }
                 else
                 {
                     Invoke((EventHandler)delegate
                     {
                         _waitBeforeLogin.Close();
                         PageCount = result.LogCountk__BackingField / PageNumber;
                         if (result.LogCountk__BackingField % PageNumber > 0) PageCount += 1;
                         CurrentPage = 1;
                         LogCount = result.LogCountk__BackingField;
                         var lbInfo =
                             string.Format(GlobalString.System_Config_String.LogPageButoomStr,
                                           LogCount, CurrentPage, PageCount, PageNumber);
                         lb_Paging.Text = lbInfo;
                         GetFileLog();
                     });
                 }

            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("backgroundWorkerGetCompanyInfo_DoWork has problem", ex);
                XtraMessageBox.Show("获取文件日志失败，请联系管理员!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                Invoke((EventHandler)delegate
                {
                    Close();
                });
            }
        }

        private int CurrentPage { get; set; }
        private int PageCount { get; set; }
        private int LogCount { get; set; }

        private void GetFileLog()
        {
            try
            {
                btn_FirstPage.Enabled = true;
                btn_PerviewPage.Enabled = true;
                btn_NextPage.Enabled = true;
                btn_LastPage.Enabled = true;
                lock (_lockObj)
                {
                    _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.GetFileLogStr,
                                                          GlobalString.System_Config_String.MbxInfoStr)
                    {
                        BackColor = BackColor
                    };
                    _waitBeforeLogin.Hide();
                }
                var backgroundWorkerGetFileLog = new BackgroundWorker();
                backgroundWorkerGetFileLog.DoWork += backgroundWorkerGetFileLog_DoWork;
                var fileQueryLogPage = new FilelogQueryPageArgs
                                           {
                                               CurrentPagek__BackingField = CurrentPage - 1,
                                               FileSidCollectionk__BackingField = _fileSidCollection.ToArray(),
                                               SkipNumberk__BackingField = PageNumber
                                           };
                backgroundWorkerGetFileLog.RunWorkerAsync(fileQueryLogPage);
                _waitBeforeLogin.ShowDialog();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("FileLogs_Shown has problem", ex);
                XtraMessageBox.Show("获取文件日志失败，请联系管理员!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
            }
        }

        void backgroundWorkerGetFileLog_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var args = e.Argument as FilelogQueryPageArgs;
                var result = fileService.GetFileLog(args);
                if (!IsHandleCreated)
                    CreateHandle();
                if (result.ResultExceptionk__BackingField == BaseExceptionEnum.GetFileLogException)
                {
                    XtraMessageBox.Show("远程服务器异常，请联系管理员!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    Invoke((EventHandler)delegate
                    {
                        Close();
                    });
                }
                else
                {
                    Invoke((EventHandler)delegate
                    {
                        SetControlEnable();
                        _waitBeforeLogin.Close();
                        var lbInfo = string.Format(GlobalString.System_Config_String.LogPageButoomStr,
                                                                LogCount, CurrentPage, PageCount, PageNumber);
                        lb_Paging.Text = lbInfo;
                        dgvLogList.DataSource = result.Resultk__BackingField;
                    });
                }

            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("backgroundWorkerGetCompanyInfo_DoWork has problem", ex);
                XtraMessageBox.Show("获取文件日志失败，请联系管理员!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                Invoke((EventHandler)delegate
                {
                    Close();
                });
            }
        }
    }
}
